#required modules: identify, ImageMagick

process_img()
{
size=$1
src_file=$2
dst_file=$3
size_opt="$size"x"$size"

#<<1>>. resize the image to let the short-side become 256 pixel. Aspect ratio preserved.
convert $src_file -resize $size_opt^ $dst_file

#<<2>>. crop the long-side to make it 256 pixel. The preserved region is at the center of image. 
width=$(identify $dst_file | awk '{print $3}' | cut -d'x' -f 1)
height=$(identify $dst_file | awk '{print $3}' | cut -d'x' -f 2)
if [ "$width" -eq "$size" ]; then
# height is the long-side. Calculte how much it should be cropped.
  crop_size=$(($height - $size))
  crop_size_1=$(($crop_size / 2))
  mogrify -crop $size_opt+0+$crop_size_1 $dst_file
#  crop_size_2=$(($crop_size - $crop_size_1))  
#  convert test.JPEG -crop $size_opt+0+$crop_size_1 test2.JPEG
else
# width is the long-side. Calculte how much it should be cropped.
  crop_size=$(($width - $size))
  crop_size_1=$(($crop_size / 2))
  mogrify -crop $size_opt+$crop_size_1+0 $dst_file
#  crop_size_2=$(($crop_size - $crop_size_1))
#  convert test.JPEG -crop $size_opt+$crop_size_1+0 test2.JPEG
fi
}

#process_folder()
#{
size=$1
src_dir=$2
dst_dir=$3
file_suffix=$4

mkdir -p $dst_dir
for img in $src_dir/*.$file_suffix
do
  file_name=`expr $img : "$src_dir/\(.*\)"`
  dst_file=$dst_dir/$file_name
  process_img $size $img $dst_file
done
#}

#mega_folder=$2
#DIRS=`ls -l $mega_folder | egrep '^d' | awk '{print $9}'`
#./parallel -j 12 process_folder $1 $mega_folder/{} $3/$DIR $4 ::: $DIRS
#echo $DIRS
#./parallel -j 12 echo {} ::: $DIRS
#for DIR in $DIRS 
#do
#  dst_dir=$3/$DIR
#  echo $mega_folder/$DIR TO $dst_dir
#  process_folder $1 $mega_folder/$DIR $dst_dir $4
#done


